/**
 * 
 */
var initPosFlag = new Boolean(false);
var initPos;
var initPosMarker;
var endPos;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var distance;
var directions;
var elevation 
var elevationPath = [];
var Path = [];
var anterior;
var routes = new google.maps.MVCArray();


$(document).ready(function() {
	//Añadir funciones a eventos de los elementos de la pagina
	//Los eventos de Google Maps no se pueden gestionar así
	$("#saveLink").click(function(){
		$("#saveForm:visible").hide("slow");
		$("#saveForm:hidden").show("slow");
		return false;
	});
});

$(window).load(function (){
	initialize();
});

function initialize() {
	
	//Get the user location via W3C standard
	var initialLocation =new google.maps.LatLng(42.846406,-2.667893);
	//Create the map
	
	createMapOff(initialLocation,"crosshair");	
	
	//Create custom controls
	createControls();

   
	//Create the Direction Display
	var rendererOptions = {
		draggable: true
	};
	directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    
    //Add event listener to the click event
    google.maps.event.addListener(map, 'click', setWaypoint);
    //Add event listener to manage direction changes
    google.maps.event.addListener(directionsDisplay, 'directions_changed', directionsChangedHandler);
    
    initialLocation = locateUser();
}

function createControls(){
	//Create resetControl
	var resetControlDiv = document.createElement('DIV');
	var resetControl = new ResetControl(resetControlDiv, map);

	resetControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(resetControlDiv);
	
	//Create UndoControl

	var undoControlDiv = document.createElement('DIV');
	var undoControl = new UndoControl(undoControlDiv, map);

	undoControlDiv.index = 2;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(undoControlDiv);
	
}

function setWaypoint(event) {
	
	if(initPosFlag == false){
		initPosMarker = new google.maps.Marker({
		    position: event.latLng,
		    map: map
		});
		
		initPosFlag=true;
		initPos=event.latLng;
		anterior=event.latLng;
		routes.push(event.latLng);
		
	}
	else{
	
	  
       routes.push(event.latLng);
      
       drawPolyline(routes,false);
      
	   document.getElementById('submit').disabled=false;
	  
	   anterior=event.latLng;
	
	   //document.getElementById('submit').disabled=true;
	   //alert(routes.getArray());
	   
	 //$("#distanceTime").slideDown("slow");
	 $("#saveRoute").slideDown("slow");
	 
	   
	}
}
function drawDirection(result, status){
	if (status == google.maps.DirectionsStatus.OK) {
      directions=result.routes[0];
      initPosMarker.setMap(null);
      directionsDisplay.setMap(map);
      directionsDisplay.setDirections(result);
      document.getElementById('submit').disabled=false;
    }
}

function directionsChangedHandler() {
	directions=directionsDisplay.directions.routes[0];
    computeRouteDetails(directionsDisplay.directions);
    drawElevation(directionsDisplay.directions.routes[0].overview_path);
    if(elevationMarker!=null){
    	elevationMarker.setVisible(false);
    }
    if(maxElevationMarker!=null && minElevationMarker!=null){
    	maxElevationMarker.setVisible(false);
		minElevationMarker.setVisible(false);
    }
    infoWindow.close();
}

function computeRouteDetails(result) {
	var timeMillis= 0;
	var time;
	var myroute= result;
	distance=0;
	for (i = 0; i < myroute.legs.length; i++) {
		
		distance += myroute.legs[i].distance.value;
	}
	distance = distance / 1000.;
	getTimeForDistance(distance);
	
	elevation=getElevation(myroute.overview_path);
	
  
 

	
}

function clearInfoTable(){
	document.getElementById("routeDetailsTable").rows[1].cells[0].innerHTML = "0 km";
	document.getElementById("routeDetailsTable").rows[3].cells[0].innerHTML = "0 h";
}

function resetMap(){
	directionsDisplay.setMap(null);
	initPosFlag=false;
	if(initPosMarker!=null){
		initPosMarker.setMap(null);
	}
	if(elevationMarker!=null){
		elevationMarker.setVisible(false);
	}
	if(maxElevationMarker!=null && minElevationMarker!=null){
    	maxElevationMarker.setVisible(false);
		minElevationMarker.setVisible(false);
    }
	document.getElementById("elevation_chart").innerHTML="";
	document.getElementById('submit').disabled=true;
	infoWindow.close();
	clearInfoTable();
	routes.clear();
}

function ResetControl(controlDiv, map) {
	// Set CSS styles for the DIV containing the control
	// Setting padding to 5 px will offset the control
	// from the edge of the map
	controlDiv.style.padding = '5px';

	// Set CSS for the control border
	var controlUI = document.createElement('DIV');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.borderStyle = 'solid';
	controlUI.style.borderWidth = '2px';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = 'Click to reset the map';
	controlDiv.appendChild(controlUI);

	// Set CSS for the control interior
	var controlText = document.createElement('DIV');
	controlText.style.fontFamily = 'Arial,sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.paddingLeft = '4px';
	controlText.style.paddingRight = '4px';
	controlText.innerHTML = 'Reset';
	controlUI.appendChild(controlText);

	// Setup the click event listeners: simply set the map to Chicago
	google.maps.event.addDomListener(controlUI, 'click', resetMap);
	
}

function UndoControl(controlDiv, map) {
	// Set CSS styles for the DIV containing the control
	// Setting padding to 5 px will offset the control
	// from the edge of the map
	controlDiv.style.padding = '5px';

	// Set CSS for the control border
	var controlUI = document.createElement('DIV');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.borderStyle = 'solid';
	controlUI.style.borderWidth = '2px';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = 'Click to undo the last moviment';
	controlDiv.appendChild(controlUI);

	// Set CSS for the control interior
	var controlText = document.createElement('DIV');
	controlText.style.fontFamily = 'Arial,sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.paddingLeft = '10px';
	controlText.style.paddingRight = '10px';
	controlText.innerHTML = 'Undo';
	controlUI.appendChild(controlText);

	// Setup the click event listeners: simply set the map to Chicago
	google.maps.event.addDomListener(controlUI, 'click', undoLine);
	
}

function undoLine(){
	
	routes.pop();
	drawPolyline(routes,true);
	//drawPolyline(routes,false);
	
}

function fillRouteData(){
	//var kmlDirection="";
	//GUARDAR SOLO EL OVERVIEW	
	//for (var i = 0; i < directions.overview_path.length; i++) {
		//kmlDirection+=""+directions.overview_path[i].lng()+","+directions.overview_path[i].lat()+" ";
	//}
//	for (var i = 0; i < directions.legs.length; i++) {
//		var leg=directions.legs[i];
//		for(var j = 0; j<leg.steps.length; j++){
//			var step=leg.steps[j];
//			for(var k=0; k<step.path.length; k++){
//				kmlDirection+=""+step.path[k].lng()+","+step.path[k].lat()+" ";
//			}
//		}
//	}

   
    
   
   
    //alert ("Enviamos los datos!!");

   
	document.getElementById('route').value=lineToKML(routes.getArray());
	document.getElementById('distance').value=distance;
	document.getElementById('elevation').value=datos;
	
	
	

}

function validateForm(form){
	if(form.routeName.value=="" || form.routeDescrip.value==""){
		alert("Introduzca un nombre y una descripción para la ruta");
		return false;
	}
	return true;
}